<script>
    // 当前的订阅者
    let activeEffect;
    // 依赖追踪类
    class Dep {
        // 订阅者集合
        subscribers = new Set();
        // 添加订阅者
        depend() {
            if (activeEffect) {
                this.subscribers.add(activeEffect);
            }
        }
        // 通知订阅者
        notify() {
            this.subscribers.forEach(effect => {
                effect()
            })
        }
    }
    // 保留此次订阅
    function watchEffect(effect) {
        activeEffect = effect;
        effect();
        activeEffect = null;
    }

    // 存储所有的值
    const targetMap = new WeakMap();
    // 获取到当前的dep对象
    function getDep(target, key) {
        // 判断在targetMap中是否有目标对象
        let depsMap = targetMap.get(target);
        if (!depsMap) {
            depsMap = new Map();
            targetMap.set(target, depsMap)
        }
        // 判断是否key在depsMap对象中
        let dep = depsMap.get(key)
        if (!dep) {
            dep = new Dep();
            // 添加dep对象至depsMap对象中
            depsMap.set(key, dep)
        }
        return dep;
    }
    // reactiveHandlers声明了代理target的指定行为
    const reactiveHandlers = {
        get(target, key, receiver) {
            const dep = getDep(target, key);
            dep.depend();
            return Reflect.get(target, key, receiver);
        },
        set(target, key, value, receiver) {
            const dep = getDep(target, key);
            const result = Reflect.set(target, key, value, receiver);
            dep.notify();
            return result;
        },
    }
    // 双向绑定代理
    function reactive(raw) {
        return new Proxy(raw, reactiveHandlers)
    }
    const state = reactive({
        count: 0
    });
    watchEffect(() => {
        console.log(state.count )
    })
    state.count++;
</script>